//
// Created by v on 19-7-2.
//

#ifndef JKLIBS_CMCOAPSERVER_H
#define JKLIBS_CMCOAPSERVER_H

#include <iostream>
#include <list>
#include <map>
#ifdef WITH_COAP
#include <coap2/coap.h>
#endif

class CMCoapFunction
{
  public:
    virtual int onRecvData(const char *url, std::string data,
                           std::string &respData)
    {
        return 0;
    }
};

typedef int (*cmdCallback)(size_t len, const char *data, void *priv);

class CMCoapServer
{
  public:
    CMCoapServer(const char *addr, int port);
    ~CMCoapServer();

    void setCoapCallback(CMCoapFunction *callback) { m_callback = callback; }

    // must call before init.
    void setDebug(bool d) { m_debug = d; }
    int  getDebug() { return m_debug; }

    int init();
    int deinit();
    // @method 1: get 2 post
    int addResource(const char *url, int method = 2);

    int run_once();

    // only call once in whole process
    static void startup();
    static void cleanup();

    CMCoapFunction *m_callback;

  protected:
    int initContext();

  private:
#ifdef WITH_COAP
    coap_context_t * m_ctx;
    coap_session_t * m_broadSession;
    coap_resource_t *m_res;
#endif

    bool m_inited;
    bool m_debug;

    std::string m_addr;
    int         m_port;
};

#endif // JKLIBS_CMCOAPSERVER_H
